package op.core.framework.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import op.core.common.utils.web.XuserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 创建和修改
 *
 * @author xuan🐽
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {

    Object createBy = getFieldValByName(DataBaseConstant.CREATE_BY, metaObject);
    if (createBy == null) {
      setFieldValByName(DataBaseConstant.CREATE_BY, XuserUtil.getUser().getId(), metaObject);
    }

    Object createDate = getFieldValByName(DataBaseConstant.CREATE_DATE, metaObject);
    if (createDate == null) {
      setFieldValByName(DataBaseConstant.CREATE_DATE, LocalDateTime.now(), metaObject);
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    updateByAndDate(metaObject);
  }

  private void updateByAndDate(MetaObject metaObject) {

    Object updateBy = getFieldValByName(DataBaseConstant.UPDATE_BY, metaObject);
    if (updateBy == null) {
      setFieldValByName(DataBaseConstant.UPDATE_BY, XuserUtil.getUser().getId(), metaObject);
    }

    Object updateDate = getFieldValByName(DataBaseConstant.UPDATE_DATE, metaObject);
    if (updateDate == null) {
      setFieldValByName(DataBaseConstant.UPDATE_DATE, LocalDateTime.now(), metaObject);
    }
  }

}
